//
//  ViewController.swift
//  xiaoqiao
//
//  Created by 冷子豪 on 2017/6/1.
//  Copyright © 2017年 冷子豪. All rights reserved.
//

import UIKit

class LoginViewController: UIViewController {

    @IBOutlet weak var usrNameLabel: UITextField!
    @IBOutlet weak var passwdLabel: UITextField!
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }
    
    /// 点击 “登录” 按钮
    ///
    /// - Parameter sender: <#sender description#>
    @IBAction func buttonTap(_ sender: UIButton) {
        
        let username = usrNameLabel.text?.trimmingCharacters(in: NSCharacterSet.whitespaces);
        let password = passwdLabel.text?.trimmingCharacters(in: NSCharacterSet.whitespaces);
        // flag ->  0   账户不存在
        //          1   登陆成功
        //          2   账户密码不匹配
        
        // 初始化 Alert Controller，设置Actions
        let alertController = UIAlertController(title: "警告", message: "", preferredStyle: .alert)
        let confirmAction = UIAlertAction(title: "确认", style: .default){ (action) -> Void in
        }
        //添加 Actions，添加的先后和显示的先后顺序是有关系的
        alertController.addAction(confirmAction)
        // alertController.addAction(cancelAction)
        
        // 校验账户密码 不为空
        guard (username != "") && (password != "") else{
            alertController.message = "账户与密码不能为空"
            self.present(alertController, animated: true, completion: nil)
            return
        }
        
        // 后台验证登录
        let flag = userViewModel.checklogin(username: username!, password: password!)
//        let flag = "1"
        
        
        switch flag {
        case "0":
            // 账户不存在 弹出提示框
            alertController.message = "账户不存在"
            self.present(alertController, animated: true, completion: nil)
        case "1":
            // 登录成功时，获取账号信息
            user = userViewModel.getUserByPhone(phone: username!)
            performSegue(withIdentifier: "login2main", sender: self)
        case "2":
            // 账户或者密码错误 弹出提示框
            alertController.message = "账户密码不匹配"
            self.present(alertController, animated: true, completion: nil)
        default:
            // 未知错误
            alertController.message = "未知错误"
            self.present(alertController, animated: true, completion: nil)
        }
    }
    
    /// 点击 “注册” 按钮
    ///
    /// - Parameter sender: <#sender description#>
    @IBAction func registerTap(_ sender: UIButton) {
        
    }
}

